package shm;

import org.apache.tomcat.jni.Proc;
import org.apache.tomcat.jni.Procattr;
import org.apache.tomcat.jni.Status;

/**
 * License: Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
 * <p/>
 * Author: Ashwin Jayaprakash
 * <p/>
 * Email: ashwin.jayaprakash@gmail.com
 * <p/>
 * Web: http://www.ashwinjayaprakash.com
 */
public class ProcCommon extends AbstractCommon {
    public static long launchChildProcess(long poolH, String programName,
                                          String[] args, String[] env, String workingDir)
            throws org.apache.tomcat.jni.Error {
        long procAttrH = Procattr.create(poolH);
        Procattr.cmdtypeSet(procAttrH, Proc.APR_PROGRAM);
        Procattr.dirSet(procAttrH, workingDir);

        long procH = Proc.alloc(poolH);
        Proc.create(procH, programName, args, env, procAttrH, poolH);

        return procH;
    }

    public static void waitForChildProcess(long procH) {
        int[] childExitCode = new int[2];
        int childProcCode = Proc.wait(procH, childExitCode, Proc.APR_WAIT);


        String exitMsg = "";
        if ((childExitCode[1] & Proc.APR_PROC_SIGNAL) == 1) {
            exitMsg = ". Received a signal";
        }
        else if ((childExitCode[1] & Proc.APR_PROC_SIGNAL_CORE) == 1) {
            exitMsg = ". Received a signal and code dumped";
        }


        switch (childProcCode) {
            case Status.APR_CHILD_DONE:
                sout("Child completed" + exitMsg);
                break;

            case Status.APR_CHILD_NOTDONE:
                sout("Child has not completed" + exitMsg);
                break;

            default:
                sout("Child status unknown");
        }
    }
}
